import { _decorator, } from 'cc';
import { CCGlobal, UrseStat } from '../util/CCGlobal';
import { CCComFun } from '../util/CCComFun';
import engine from '../../Engine';
const { ccclass, property } = _decorator;

@ccclass('StatisticsBase')
export class StatisticsBase {

    private static instance: any = null;
    public static getInstance<T>(c: { new(): T }) {
        if (!this.instance) {
            this.instance = new c();
        }
        return this.instance;
    }


    /**启动参数 */
    public launchOptionsSync = null;
    /**上报参数 */
    private queryString: string[] = [];

    /**用户注册时间 */
    private get userRegtime() {
        let temp = engine.localStorage.getItem("userRegtime");
        if (!temp) {
            temp = this.currentTime();
            engine.localStorage.setItem("userRegtime", temp);
        }
        return temp;
    }


    /**基础属性 */
    protected get basicAB() {
        return {
            platform: CCGlobal.PLATFORM,
            gameName: CCGlobal.GameType,
            openID: UrseStat.openid,
            versioncode: CCGlobal.Version,
        }
    }


    /**构建请求 */
    protected buildUrl(keyValues) {
        if (engine.cc_debug) { return };
        let project = "gjswd";
        let host = "cn-zhangjiakou.log.aliyuncs.com";
        let baseUrl = `https://${project}.${host}/logstores/${project}/track?APIVersion=0.6.0`;
        keyValues = this.objectToQueryString(keyValues);
        baseUrl += `&${keyValues}`;

        CCGlobal.API.request({
            url: baseUrl,
            method: "GET",
            success: () => {
                CCComFun.StatLog(`${baseUrl}请求成功`);
            },
            fail: (err) => {
                CCComFun.StatLog(`${baseUrl}请求失败${JSON.stringify(err)}`);
            }
        })
    }

    /**调试请求 */
    protected debugLogUrl(keyValues) {
        if (engine.cc_debug) { return };
        let project = "gjswd";
        let host = "cn-zhangjiakou.log.aliyuncs.com";
        let baseUrl = `https://${project}.${host}/logstores/testlog/track?APIVersion=0.6.0`;
        keyValues = this.objectToQueryString(keyValues);
        baseUrl += `&${keyValues}`;

        CCGlobal.API.request({
            url: baseUrl,
            method: "GET",
            success: () => {
                CCComFun.StatLog(`${baseUrl}请求成功`);
            },
            fail: (err) => {
                CCComFun.StatLog(`${baseUrl}请求失败${JSON.stringify(err)}`);
            }
        })
    }

    /**获取OpenID */
    protected getOpenid(loginConfig) {
        let params = new URLSearchParams({
            appid: CCGlobal.Config.appId,
            code: loginConfig.code,
            anonymous_code: loginConfig.anonymousCode
        })
        let requestUrl = `${CCComFun.statConfig.openId}?${params.toString()}`;
        //    console.log("get url:", requestUrl)
        CCGlobal.API.request({
            url: requestUrl,
            method: "GET",
            success: (response) => {
                //   console.log("Response:", JSON.stringify(response));
                if (response && response.data) {
                    let openid = response.data.openid;
                    if (openid) {
                        UrseStat.openid = openid;
                        //        console.log("openid:", UrseStat.openid);
                        this.ecpmUser();
                    }
                }
            },
        })
    }

    /**用户ecpm */
    protected ecpmUser() {
        if (!this.launchOptionsSync.query.clickid) {
            return;
        }

        let data = {
            callback: this.launchOptionsSync.query.clickid,
            creativeid: this.launchOptionsSync.creativeid,
            openid: UrseStat.openid,
            app_id_ks: CCGlobal.Config.appId,
            regtime: this.userRegtime,
            advertiser_id: this.launchOptionsSync.query.advertiser_id,
            event_time: this.currentTime(),
        }
        //  console.log(JSON.stringify(data));
        CCComFun.StatLog(`ecpmUser : ${JSON.stringify(data)}`);
        CCGlobal.API.request({
            url: CCComFun.statConfig.ecpmUser,
            method: "POST",
            data: JSON.stringify(data),
            success: (code) => {
                // console.log(`ecpmUser 成功: ${this.stringify(code)}`)
                CCComFun.StatLog(`ecpmUser 成功: ${this.stringify(code)}`);
                this.debugLogUrl({
                    ecpmUser: data
                });
            },
            fail: (err) => {
                CCComFun.StatLog(`ecpmUser 失败: ${this.stringify(err)}`);
            }
        })
    }


    /**对象转字符串 */
    protected objectToQueryString(obj) {
        this.recurse(obj)
        return this.queryString.join('&');
    }

    /**递归转换 */
    protected recurse(currentObj) {
        this.queryString = [];

        for (let key in currentObj) {
            if (currentObj.hasOwnProperty(key)) {
                let value = currentObj[key];

                if (typeof value === 'object' && value !== null) {
                    this.recurse(value); // 递归处理嵌套对象
                } else {
                    // 将非对象的值添加到查询字符串中
                    this.queryString.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
                }
            }
        }
    }

    /**解析返回值 */
    protected stringify(data) {
        if (!data) {
            return "err :  return value is empty";
        }
        return JSON.stringify(data);
    }


    /**当前时间-13 */
    protected millisecondTimestamp() {
        let now: Date = new Date();
        let millisecondTimestamp: number = now.getTime();
        return millisecondTimestamp;
    }

    /**当前时间-10 */
    protected currentTime() {
        let now: Date = new Date();
        let millisecondTimestamp: number = now.getTime();
        let secondTimestamp: number = Math.floor(millisecondTimestamp / 1000);
        return secondTimestamp;
    }
}


